package net.topikachu.dynamic.screen.widget;

import java.io.IOException;
import java.net.URL;

import javax.el.ELException;
import javax.faces.FacesException;
import javax.faces.component.UIComponent;

import net.topikachu.dynamci.screen.ComponentDescriptor;
import net.topikachu.dynamic.faces.WidgetExecutor;
import net.topikachu.dynamic.faces.WidgetPlaceHolderStack;

import com.sun.facelets.FaceletContext;
import com.sun.facelets.FaceletException;

public class FaceletWidget extends AbstractWidget implements Widget {

	private ComponentDescriptor componentDescriptor;

	public FaceletWidget(ComponentDescriptor d, Widget child) {
		super(child);
		this.componentDescriptor = d;
		applyDescriptorAttributes();
	}

	public URL getFacelet() {
		return this.getClass().getClassLoader().getResource(
				("net/topikachu/dynamic/screen/widget/facelet/"
						+ componentDescriptor.getType().toString() + ".xhtml"));
	}

	private void applyDescriptorAttributes() {
		if (componentDescriptor.getFiledName() != null) {
			addVariable("field", componentDescriptor.getFiledName());
		}

		if (componentDescriptor.getLabel() != null) {
			addVariable("label", componentDescriptor.getLabel());

		}
	}

	public void apply(FaceletContext ctx, UIComponent parent)
			throws IOException, FacesException, FaceletException, ELException {
		WidgetExecutor.executeWidget(ctx, parent, this);
		WidgetPlaceHolderStack stack = WidgetPlaceHolderStack.getStack(ctx);
		if (stack.hasPlaceHolder()) {
			parent = stack.pop();
		}
		child.apply(ctx, parent);

	}

}
